﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Shop.Base.Entity.View;
using Shop.Entity;
using Shop.Tools;
using Shop.Web.Models;

namespace Shop.Web.Filter
{
    /// <summary>
    /// 登录过滤器验证
    /// </summary>
    public class SignFilter : ActionFilterAttribute
    {
        /// <summary>
        /// 当动作执行中 
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            ////禁止爬虫
            //if (!context.HttpContext.Request.Headers.ContainsKey("Referer"))
            //{
            //    //强制跳转
            //    context.HttpContext.Response.StatusCode = 302;
            //    // 用户未登陆 - 跳转到登陆界面
            //    context.Result = new JsonResult("请使用浏览器访问");
            //}
            // 判断是否检查登陆
            var noNeedCheck = false;
            if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
            {
                noNeedCheck = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true).Any(a => a.GetType().Equals(typeof(NoSignAttribute)));
            }
            var userid = context.HttpContext.Session.Get<Guid>(SessionKeys.UserId);
            var signname = context.HttpContext.Session.Get<string>(SessionKeys.UserName);
            var userInfo = context.HttpContext.Session.Get<ComUser>(SessionKeys.UserInfo);
            if (noNeedCheck)
            {
                if (context.HttpContext.Request.Path.HasValue && (context.HttpContext.Request.Path.Value.ToLower().Contains("/Login/Index".ToLower()) || context.HttpContext.Request.Path.Value.ToLower().Contains("/Login".ToLower())) && !userid.IsEmptyGuid() && !signname.IsNullOrEmpty())
                {
                    context.HttpContext.Response.StatusCode = 302;
                    context.Result = new RedirectResult("/");
                }
                base.OnActionExecuting(context);
                return;
            }

            // 验证是否访问的地址是否需要登录
            if (userid.IsEmptyGuid() || signname.IsNullOrEmpty())
            {
                //强制跳转
                context.HttpContext.Response.StatusCode = 302;
                // 用户未登陆 - 跳转到登陆界面
                context.Result = new RedirectResult("/Login/Index");
            }
            //需要登录 不受权限控制
            var noPowerCheck = false;
            if (context.ActionDescriptor is ControllerActionDescriptor noPower)
            {
                noPowerCheck = noPower.MethodInfo.GetCustomAttributes(inherit: true).Any(a => a.GetType().Equals(typeof(SignNoPowerAttribute)));
            }
            if (noPowerCheck)
            {
                base.OnActionExecuting(context);
                return;
            }
            var area = context.ActionDescriptor.RouteValues["area"];
            var controller = context.ActionDescriptor.RouteValues["controller"];
            var action = context.ActionDescriptor.RouteValues["action"];


            if (!area.IsNullOrEmpty() && !userid.IsEmptyGuid() && !signname.IsNullOrEmpty())
            {
                if (!userInfo.IsNormal && !(area == "Admin" && controller == "Default" && action == "Unauthorized"))
                {
                    var menu = context.HttpContext.Session.Get<List<UserRoleFunction>>(SessionKeys.UserMenu);
                    if (menu != null && menu.Count > 0)
                    {
                        if (!menu.Any(x => x.AreaStr == area && x.ControllerStr == controller && (x.ActionStr == action || x.ButtonTag == action)) ||
                        (action == "Edit" && context.HttpContext.Request.Query.Count <= 0 && !menu.Any(x => x.AreaStr == area && x.ControllerStr == controller && (x.ActionStr == action || x.ButtonTag == action) && x.ButtonName == "新增"))
                        || (action == "Edit" && context.HttpContext.Request.Query.Count > 0 && !menu.Any(x => x.AreaStr == area && x.ControllerStr == controller && (x.ActionStr == action || x.ButtonTag == action) && x.ButtonName == "编辑")))
                        {
                            if (context.HttpContext.Request.Headers.ContainsKey("x-requested-with") && context.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest")
                            {
                                context.Result = new JsonResult(new ResultModel { code = OperationResultType.PurviewLack, data = new List<string>(), error_msg = "无权限操作", success = false });
                            }
                            else
                            {
                                //强制跳转
                                context.HttpContext.Response.StatusCode = 302;
                                // 未授权页面
                                context.Result = new RedirectResult("/Admin/Default/Unauthorized");
                            }
                        }
                    }
                    else
                    {
                        //强制跳转
                        context.HttpContext.Response.StatusCode = 302;
                        // 未授权页面
                        context.Result = new RedirectResult("/Admin/Default/Unauthorized");
                    }
                    
                }
                else if (userInfo.IsNormal)
                {
                    context.HttpContext.Response.StatusCode = 302;
                    context.Result = context.HttpContext.Request.Headers.ContainsKey("Referer") ? new RedirectResult(context.HttpContext.Request.Headers["Referer"]) : new RedirectResult("/");
                }
            }
            base.OnActionExecuting(context);
        }
    }
    /// <summary>
    /// 不需要登陆的地方加个特性
    /// </summary>
    public class NoSignAttribute : ActionFilterAttribute { }

    /// <summary>
    /// 需要登陆的地方,不授权控制加个特性
    /// </summary>
    public class SignNoPowerAttribute : ActionFilterAttribute { }
}